package com.by_man.presenter.module_health_management.measure_blood_pressure;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 查看血压记录信息activity
 * Created by man on 2017-02-16.
 */
public class CheckBloodPressureActivity extends AppCompatActivity {
    private Handler handler;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_blood_pressure);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView();
            }
        };
        if (null == UserInfos.One_BloodPressure_Record) { // 开启线程
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
            if (NetworkDataManager.BPNum < 1) {  // 对此请求后，询问用户
                showRequestAgain();
            }
            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.All_BloodPressure_Record) {  // 阻塞等待数据的初始化
                        if (NetworkDataManager.BPNum < 1) {
                            showRequestAgain();
                        }
                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        }
        else {
            initView();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, MeasureBloodPressureActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, MeasureBloodPressureActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    private void initView() {
        // 初始化toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        ListView listView = (ListView)findViewById(R.id.list_record);
        Intent intent = getIntent();
        // 取出数据
        try {
            //JSONArray jsonArray = new JSONArray(intent.getStringExtra("extra_data"));
            JSONArray jsonArray = LocalDataManager.getAllBloodPressureRecord();
            if (null != jsonArray) {
                ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
                JSONObject temp_high;
                JSONObject temp_low;
                JSONObject temp_xinlv;
                JSONObject temp_note;
                JSONObject temp;
                int m = jsonArray.length() / 3;
                if (m == 0) {   // 没有数据的处理
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("high", "");
                    map.put("low", "");
                    map.put("xinlv", "");
                    map.put("showdate", "暂无数据");
                    map.put("showtime", "");
                    map.put("type", "");
                    map.put("note", "");            // 添加备注字段   2016-12-05  bm
                    listItem.add(map);
                    SimpleAdapter adapter;
                    adapter = new SimpleAdapter(this, listItem, R.id.list_record,
                            new String[]{"showdate", "showtime", "high", "low", "xinlv", "type", "note"},
                            new int[]{R.id.showdate, R.id.showtime, R.id.high, R.id.low, R.id.heart_rate, R.id.type, R.id.note_txt});
                    listView.setAdapter(adapter);

                } else {
                    // 2016-12-05   bm
                    int count = 0;                                              // 记录匹配正确的数据项，判断匹配是否出错
                    int i = 0;                                                  // 循环变量
                    String high, low, xinlv, datetime, note, date, time, type;
                    high = low = xinlv = datetime = note = date = time = type = "";                  // 初始化
                    temp_high = temp_low = temp_xinlv = temp_note = null;
                    String date_temp = "";                                      // 记录当前时间组
                    String tempStr = "";

                    while (i < jsonArray.length()) {
                        temp = jsonArray.getJSONObject(i);                      // 取出下一组数据项的首项
                        tempStr = datetime = temp.getString("updated_at");      //  获取时间，作为数据项分界标准
                        while (i < jsonArray.length() &&                        // 保证数组不越界
                                tempStr.equals(datetime = (temp = jsonArray.getJSONObject(i)).getString("updated_at"))) {
                            if (temp.getString("data_id").equals("1")) {        // 说明是血压高值
                                temp_high = temp;
                                i++;                                              // 跳到下一项数据
                            } else if (temp.getString("data_id").equals("2")) {
                                temp_low = temp;
                                i++;
                            } else if (temp.getString("data_id").equals("4")) {
                                temp_xinlv = temp;
                                i++;
                            } else if (temp.getString("data_id").equals("7")) {
                                temp_note = temp;
                                i++;
                            } else {

                            }
                        }

                        // 分析取出的数据项
                        high = temp_high.getString("value");
                        low = temp_low.getString("value");
                        xinlv = temp_xinlv.getString("value");
                        type = temp_high.getString("type");
                        // 判断类型
                        if (type.equalsIgnoreCase("null")) {
                            type = "未知";
                        } else if (type.equalsIgnoreCase("0")) {
                            type = "手动";
                        } else {
                            type = "蓝牙";
                        }
                        // 判断是否有备注项
                        if (null == temp_note) {
                            note = "";
                        } else {
                            note = temp_note.getString("value");
                        }

                        // 判断日期是否一致
                        date = tempStr.substring(0, 10);
                        time = tempStr.substring(11, 16);
                        if (date_temp.equals(date)) {
                            date = "";
                        } else {
                            date_temp = date;
                        }

                        // 更新数据项
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        // 放入数据
                        map.put("high", high);
                        map.put("low", low);
                        map.put("xinlv", xinlv);
                        map.put("note", note);
                        map.put("showdate", date);
                        map.put("showtime", time);
                        map.put("type", type);

                        // 设置这一项数据的adapter
                        listItem.add(map);
                        SimpleAdapter adapter;
                        adapter = new SimpleAdapter(this, listItem, R.layout.check_blood_pressure_listview_item,
                                new String[]{"showdate", "showtime", "high", "low", "xinlv", "type", "note"},
                                new int[]{R.id.showdate, R.id.showtime, R.id.high, R.id.low, R.id.heart_rate, R.id.type, R.id.note_txt});
                        listView.setAdapter(adapter);

                        // 将相关数据再次初始化
                        temp_high = temp_low = temp_xinlv = temp_note = null;
                    }

                }
            }
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }

    public void showRequestAgain() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("已多次请求服务器，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NetworkDataManager.BPNum = 3;
                        LocalDataManager.getAllBloodPressureRecord();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 0);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
